﻿Imports Alsing.SourceCode

Public Class QueryResult

    Private _strCn As String
    Private _dbName As String
    Private _schemaName As String
    Private _tableName As String

    Public Sub Init(strCn As String, dbName As String, schemaName As String, tableName As String)
        Dim loader As New SyntaxDefinitionLoader()
        Dim syntax As SyntaxDefinition = loader.Load("SQLServer.syn")
        docQueryText.Parser.Init(syntax)

        _strCn = strCn
        _dbName = dbName
        _schemaName = schemaName
        _tableName = tableName
        Dim cn As New SqlClient.SqlConnection(_strCn)
        cn.Open()
        cn.Close()
        ToolStripStatusLabel1.Text = String.Format("[{0}].[{1}].[{2}] CnStr='{3}'", _dbName, _schemaName, _tableName, _strCn)
    End Sub
    Dim dt As DataTable
    Private Sub btnRun_Click(sender As System.Object, e As System.EventArgs) Handles btnRun.Click
        Try

            Dim cn As New SqlClient.SqlConnection(_strCn)
            cn.Open()
            Dim sp As New SqlClient.SqlCommand(docQueryText.Text, cn)
            dt = New DataTable
            dt.Load(sp.ExecuteReader)
            cn.Close()
            BindingSource1.DataSource = dt
            DataGridView1.AutoGenerateColumns = True
            DataGridView1.Refresh()
            TabControl1.SelectedTab = TabData
        Catch ex As Exception
            tbOutput.AppendText(String.Format("{0}" & vbCrLf, ex.Message))
            TabControl1.SelectedTab = TabMessages
        End Try

    End Sub

    Private Sub QueryResult_Activated(sender As Object, e As System.EventArgs) Handles Me.Activated
        docQueryText.Text = String.Format("select top 10 * from [{0}].[{1}].[{2}]", _dbName, _schemaName, _tableName)
    End Sub

    Private Sub QueryResult_KeyUp(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyUp
        If e.KeyData = Keys.F5 Then
            btnRun.PerformClick()
        End If
    End Sub

    Private Sub DataGridView1_DataError(sender As System.Object, e As System.Windows.Forms.DataGridViewDataErrorEventArgs) Handles DataGridView1.DataError
        e.Cancel = True
    End Sub
End Class